package com.webapps.tvprogram.utils;

import java.io.FileNotFoundException;
import java.io.IOException;
import java.net.MalformedURLException;
import java.net.ProtocolException;
import java.util.ArrayList;

import javax.xml.parsers.ParserConfigurationException;

import org.xml.sax.SAXException;

import android.os.AsyncTask;

import com.webapps.tvprogram.data.local.Program;
import com.webapps.tvprogram.web.WebRetreiver;

public class InitResourcesTask extends AsyncTask<Void, Void, ArrayList<Program>> {

    private boolean performFullUpdate;
    private MyXmlParserTaskCallback callback;
    private boolean errorOccured;

    public InitResourcesTask(boolean performFullUpdate, MyXmlParserTaskCallback callback) {
        this.performFullUpdate = performFullUpdate;
        this.callback = callback;
        errorOccured = false;
    }

    @Override
    protected ArrayList<Program> doInBackground(Void... params) {
        ArrayList<Program> programsData = null;
        try {
            if (performFullUpdate) {
                new WebRetreiver().retreiveXmlFile();
            }
            programsData = new XmlParsingHandler().parseXml(performFullUpdate);
        } catch (ParserConfigurationException e) {
            errorOccured = true;
            callback.onError(e);
            e.printStackTrace();
        } catch (SAXException e) {
            errorOccured = true;
            callback.onError(e);
            e.printStackTrace();
        } catch (MalformedURLException e) {
            errorOccured = true;
            callback.onError(e);
            e.printStackTrace();
        } catch (ProtocolException e) {
            errorOccured = true;
            callback.onError(e);
            e.printStackTrace();
        } catch (FileNotFoundException e) {
            errorOccured = true;
            callback.onError(e);
            e.printStackTrace();
        } catch (IOException e) {
            errorOccured = true;
            callback.onError(e);
            e.printStackTrace();
        }
        return programsData;
    }

    @Override
    protected void onPostExecute(ArrayList<Program> result) {
        if (!errorOccured)
            callback.onSuccess(result);
    }

    @Override
    protected void onPreExecute() {
        // TODO check preconditions
        // internet connection if we want to perform full update
        // sdcard present
        // xml file present if NOT full update
    }

    @Override
    protected void onProgressUpdate(Void... values) {
    }

}
